package com.iwinding.ladygg.ui.act;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.bluetooth.TMApi;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.callback.SosDetailCallBack;
import com.iwinding.ladygg.net.request.DealSOSReq;
import com.iwinding.ladygg.net.request.NoNoticeReq;
import com.iwinding.ladygg.net.request.PushSosReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.SosDetailRp;
import com.iwinding.ladygg.runtimepermissions.PermissionsManager;
import com.iwinding.ladygg.runtimepermissions.PermissionsResultAction;
import com.iwinding.ladygg.utils.CommonUtil;
import com.iwinding.ladygg.utils.DateUtil;
import com.iwinding.ladygg.utils.RoundedTransformation;
import com.iwinding.ladygg.utils.ToastUtil;
import com.iwinding.ladygg.widget.SlideSwitch;
import com.squareup.picasso.Picasso;

/**
 * Created by hezhiyong on 2017/4/17.
 */

public class SosDetailActivity extends BaseActivity implements LocationSource, GeocodeSearch.OnGeocodeSearchListener {

    public static final String SOSID = "sosid";
    //    public static final String CONCERN = "concern";
    public static final String ISME = "isme";

    private ImageView mImgHead;
    private TextView mTvName;
    private TextView mTvPhone;
    private TextView mTvTime;
    private TextView mTvAddress;
    private SlideSwitch mSSHandle;
    private SlideSwitch mSSFirstAid;
    private SlideSwitch mSSHelp;
    private ImageView mImgMsg;

    private View mLayALL;
    private View mVHandle;
    private View mVFirstAid;
    private View mVHelp;
    private View mVLine1;
    private View mVLine2;

    private MapView mapView;
    private AMap mAMap;

    private SosDetailRp sosDetailRp;

    public String sosid;
    //    public boolean concern;
    public boolean isme;
    public String address;//根据经纬度转换成地址

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_sos_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sosid = getIntent().getStringExtra(SOSID);
//        concern = getIntent().getBooleanExtra(CONCERN, false);
        isme = getIntent().getBooleanExtra(ISME, false);
        initView(savedInstanceState);
        initLinster();
        loadData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.removeAllViews();
            mapView.onDestroy();
        }
        if (mAMap != null) {
            mAMap.clear();
            mAMap = null;
        }
        mapView = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }


    void initView(Bundle savedInstanceState) {
        setTitleResId(R.string.icane_sos_detail);
        if (TextUtils.isEmpty(sosid)) {
            ToastUtil.openBaseToast(mContext, R.string.sosid_cannot_be_empty, Toast.LENGTH_SHORT);
            finish();
        }

        mImgHead = (ImageView) findViewById(R.id.icane_sos_img);
        mImgMsg = (ImageView) findViewById(R.id.icane_sos_img_msg);
        mTvName = (TextView) findViewById(R.id.icane_sos_name);
        mTvPhone = (TextView) findViewById(R.id.icane_sos_phone);
        mTvTime = (TextView) findViewById(R.id.icane_sos_send_time);
        mTvAddress = (TextView) findViewById(R.id.detial_text_address);
        mSSHandle = (SlideSwitch) findViewById(R.id.icane_sos_handle_switch);
        mSSFirstAid = (SlideSwitch) findViewById(R.id.icane_sos_first_aid_switch);
        mSSHelp = (SlideSwitch) findViewById(R.id.icane_sos_for_help_switch);
        mLayALL = findViewById(R.id.lay_handle_button);
        mVHandle = findViewById(R.id.lay_handle);
        mVFirstAid = findViewById(R.id.lay_first_aid);
        mVHelp = findViewById(R.id.lay_for_help);
        mVLine1 = findViewById(R.id.icane_handle_line);
        mVLine2 = findViewById(R.id.icane_first_line);
        mapView = (MapView) findViewById(R.id.detial_map);
        mapView.onCreate(savedInstanceState);
        initBaiduMap();
    }

    void initLinster() {
        mSSHandle.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open() {
                setHandle();
            }

            @Override
            public void close() {

            }
        });
        mSSFirstAid.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open() {
                setNotice(true);
            }

            @Override
            public void close() {
                setNotice(false);
            }
        });
        mSSHelp.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open() {

            }

            @Override
            public void close() {
                setClearHelp();
            }
        });

        mTvPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionsResultAction action = new PermissionsResultAction() {
                    @Override
                    public void onGranted() {
                        callPhone();
                    }

                    @Override
                    public void onDenied(String permission) {
                        ToastUtil.openBaseToast(mContext,permission,Toast.LENGTH_SHORT);
                    }
                };
                PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(SosDetailActivity.this, new String[]{Manifest.permission.CALL_PHONE}, action);
            }
        });

//        mSSHandle.setOnClickListener(this);
//        mSSFirstAid.setOnClickListener(this);
    }

    void callPhone(){
        // 获取号码
        String number = mTvPhone.getText().toString();
        if (TextUtils.isEmpty(number)){
            // 提醒用户
            // 注意：在这个匿名内部类中如果用this则表示是View.OnClickListener类的对象，
            // 所以必须用MainActivity.this来指定上下文环境。
            Toast.makeText(mContext, "号码不能为空！", Toast.LENGTH_SHORT).show();
        }else{
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    void initBaiduMap() {
        mAMap = mapView.getMap();

        mAMap.setMapType(AMap.LOCATION_TYPE_LOCATE);
        mAMap.setMaxZoomLevel(20);//设置地图的缩放级别,缩放级别为4-20级
        mAMap.setMinZoomLevel(4);//设置地图的缩放级别,缩放级别为4-20级
        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.getUiSettings().setAllGesturesEnabled(false); // 是否显示默认的定位按钮
        mAMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
        mAMap.getUiSettings().setTiltGesturesEnabled(false);// 设置地图是否可以倾斜
        mAMap.getUiSettings().setScaleControlsEnabled(true);// 设置地图默认的比例尺是否显示
        mAMap.getUiSettings().setZoomControlsEnabled(true);
        mAMap.getUiSettings().setGestureScaleByMapCenter(true);//以地图中心缩放
        mAMap.getUiSettings().setAllGesturesEnabled(true);
        mAMap.setMyLocationRotateAngle(180);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(20));
        // 隐藏缩放控件
        int childCount = mapView.getChildCount();
        View zoom = null;
        for (int i = 0; i < childCount; i++) {
            View child = mapView.getChildAt(i);
            if (child instanceof ZoomControls) {
                zoom = child;
                break;
            }
        }

        if (zoom != null)
            zoom.setVisibility(View.GONE);
    }

    void loadData() {
        PushSosReq req = new PushSosReq();
        req.sosId = sosid;
        RequestManager.postSosDetail(mContext, req, new SosDetailCallBack() {
            @Override
            public void onResult(SosDetailRp sosDetailRp) {
                setSosDetailRp(sosDetailRp);
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    void setSosDetailRp(SosDetailRp sosDetailRp) {
        address = sosDetailRp.address;
        this.sosDetailRp = sosDetailRp;
        if (!TextUtils.isEmpty(sosDetailRp.headImg)) {
            String url = CommonUtil.utf8Togb2312(sosDetailRp.headImg);
            Picasso.with(mContext).load(url).transform(new RoundedTransformation(9, 0)).into(mImgHead);
        }
        mTvName.setText(TextUtils.isEmpty(sosDetailRp.nickName) ? (TextUtils.isEmpty(sosDetailRp.uname) ? "" : sosDetailRp.uname) : sosDetailRp.nickName);
        mTvPhone.setText(TextUtils.isEmpty(sosDetailRp.mobile) ? "" : sosDetailRp.mobile);
        String time;
        try {
            time = DateUtil.getTime(sosDetailRp.sendTime);
        } catch (Exception e) {
            time = sosDetailRp.sendTime;
        }
        mTvTime.setText(time);
        mTvAddress.setVisibility(TextUtils.isEmpty(address)?View.GONE:View.VISIBLE);
        mTvAddress.setText(TextUtils.isEmpty(address)?"":address);

        switch (sosDetailRp.status) {
            case 0:
                initDisCard();
                break;
            case 1:
                initFinished();
                break;
            case 2:
                initDoing();
                break;
        }

        if (!TextUtils.isEmpty(sosDetailRp.latitude) || !TextUtils.isEmpty(sosDetailRp.longitude))
            setMapContent(sosDetailRp);

    }

    //作废
    void initDisCard() {
        mImgMsg.setVisibility(View.VISIBLE);
        mImgMsg.setImageResource(R.mipmap.message_sos_discard);
        mLayALL.setVisibility(View.GONE);
    }

    //已完成
    void initFinished() {
        mImgMsg.setVisibility(View.VISIBLE);
        mImgMsg.setImageResource(R.mipmap.message_sos_finished);
        mLayALL.setVisibility(View.GONE);
    }

    //处理中
    void initDoing() {
        mImgMsg.setVisibility(View.INVISIBLE);
        mSSHandle.setState(sosDetailRp.status == 1);

        //处理是否关注
        boolean isConcern = false;
        if (!TextUtils.isEmpty(sosDetailRp.isConcern) && TextUtils.equals(sosDetailRp.isConcern, "1")) {
            isConcern = true;
        }

        mSSFirstAid.setState(isConcern);
//        if (isConcern) {
//
//        } else {
//            mVLine1.setVisibility(View.GONE);
//            mVFirstAid.setVisibility(View.GONE);
//        }

        // 寻求帮助
        if (isme) {
            mVHandle.setVisibility(View.GONE);//关注隐藏
            mVLine1.setVisibility(View.GONE);
            mVFirstAid.setVisibility(View.GONE);//是否关注隐藏
            mVLine2.setVisibility(View.GONE);
        } else {
            mVHelp.setVisibility(View.GONE);//隐藏寻求帮助
        }
    }


    void setMapContent(SosDetailRp sosDetailRp) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(Double.parseDouble(sosDetailRp.latitude), Double.parseDouble(sosDetailRp.longitude)), 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
        //定位成功下
        if (sosDetailRp != null) {


            MyLocationStyle myLocationStyle = new MyLocationStyle()
                    .myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)
                    .anchor(Float.parseFloat(sosDetailRp.latitude), Float.parseFloat(sosDetailRp.longitude))
//                    .strokeColor(Color.argb(0, 0, 0, 0))// 设置圆形的边框颜色
//                    .radiusFillColor(Color.argb(0, 0, 0, 0))// 设置圆形的填充颜色
//                    .strokeWidth(0f)// 设置圆形的边框粗细
                    .showMyLocation(true);
            mAMap.setMyLocationStyle(myLocationStyle);// 设置为跟随模式,显示手机方向的箭头
            mAMap.clear();
            mAMap.setMyLocationStyle(myLocationStyle);
            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.parseFloat(sosDetailRp.latitude),
                    Float.parseFloat(sosDetailRp.longitude)), 17));
            mAMap.clear();
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(new LatLng(Float.parseFloat(sosDetailRp.latitude),
                    Float.parseFloat(sosDetailRp.longitude)));
            markerOption.title(address);
            markerOption.visible(true);
            Marker marker = mAMap.addMarker(markerOption);
//            MarkerOptions markerOption = new MarkerOptions();
//            markerOption.position(new LatLng(Float.parseFloat(sosDetailRp.latitude),
//                    Float.parseFloat(sosDetailRp.longitude)));
//            markerOption.title(sosDetailRp.uname).snippet(sosDetailRp.uname + ":" + sosDetailRp.mobile);
//            markerOption.visible(true);
//            Marker marker = mAMap.addMarker(markerOption);

        }
    }

    public void setHandle() {
        DealSOSReq req = new DealSOSReq();
        req.sosId = sosid;
        RequestManager.postDealSOS(mContext, req, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse o) {
                initFinished();
                mSSHandle.setEnabled(false);
                TMApi.getInstance().handleSos(sosid, address, sosDetailRp);
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }

        });
    }

    public void setNotice(boolean isOpen) {
        NoNoticeReq noNoticeReq = new NoNoticeReq();
        noNoticeReq.isConcern = isOpen ? 1 : 0;
        noNoticeReq.sosId = sosid;
        RequestManager.postNoNotice(mContext, noNoticeReq, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse o) {

            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }

        });
    }

    public void setClearHelp() {
        DealSOSReq req = new DealSOSReq();
        req.sosId = sosid;
        RequestManager.postCancelSOS(mContext, req, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse o) {
                initDisCard();
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }

        });
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
//        setMapContent(sosDetailRp);
    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (regeocodeResult != null) {
            mAMap.clear();
            address = regeocodeResult.getRegeocodeAddress().getFormatAddress();
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(new LatLng(Float.parseFloat(sosDetailRp.latitude),
                    Float.parseFloat(sosDetailRp.longitude)));
            markerOption.title(TextUtils.isEmpty(sosDetailRp.nickName) ? (TextUtils.isEmpty(sosDetailRp.uname) ? "" : sosDetailRp.uname) : sosDetailRp.nickName).snippet(address);
            markerOption.visible(true);
            Marker marker = mAMap.addMarker(markerOption);
            mTvAddress.setText(address);
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

}
